package com.healtyprj.rsa;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class RsaUtils {
	
	private static final String CIPHER_ALGORITHM = "RSA";
	private static final String CIPHER_MODE = CIPHER_ALGORITHM + "/ECB/PKCS1PADDING";
	
	private Cipher cipher;
	private Key privateKey;
	private Key publicKey;
	
	public RsaUtils() {
		super();
	}
	
	public RsaUtils(String privateKeyPath, String publicKeyPath) {
		this();
		initialize();
		loadKey(privateKeyPath, publicKeyPath);
	}
	
	public byte[] encryptWithPrivateKey(byte[] source) {
		try {
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			return cipher.doFinal(source);
		} catch (GeneralSecurityException e) {
			throw new RuntimeException(e);
		}
	}

	public String decryptWithPublicKey(byte[] source) {
		try {
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			return new String(cipher.doFinal(source), "UTF-8");
		} catch (GeneralSecurityException e) {
			throw new RuntimeException(e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
	private void initialize() {
		try {
			cipher = Cipher.getInstance(CIPHER_MODE);
		} catch (GeneralSecurityException e) {
			throw new RuntimeException(e);
		}
	}
	
	private void loadKey(String privateKeyPath, String publicKeyPath) {
		try {
			KeyFactory keyfactory = KeyFactory.getInstance(CIPHER_ALGORITHM);
			KeySpec keyspec;

			if (privateKeyPath != null
					&& !privateKeyPath.isEmpty()) {
				keyspec = new PKCS8EncodedKeySpec(loadBinaryFile(privateKeyPath));
				privateKey = keyfactory.generatePrivate(keyspec);
			}

			if (publicKeyPath != null
					&& !publicKeyPath.isEmpty()) {
				keyspec = new X509EncodedKeySpec(loadBinaryFile(publicKeyPath));
				publicKey = keyfactory.generatePublic(keyspec);
			}
		} catch (GeneralSecurityException e) {
			throw new RuntimeException(e);
		}
	}
	
	private static byte[] loadBinaryFile(String filename) {
		try {
			FileInputStream in = new FileInputStream(filename);
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();
			return data;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return new byte[0];
	}
}
